import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '../store'
const originalPush = VueRouter.prototype.push;
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err);
}

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    component: () => import('../components/index.vue'),
    redirect: "/home",
    name: "index",
    children: [{
      path: "/login",
      name: "login",
      component: () => import('../components/user/login.vue')
    }, {
      path: "/articlePage",
      name: "articlePage",
      component: () => import('../components/article/page.vue')
    }, {
      path: "/article",
      name: "article",
      component: () => import('../components/article/index')
    }, {
      path: "/notice",
      name: "notice",
      component: () => import('../components/notice/index.vue')
    }, {
      path: "/about",
      name: "about",
      component: () => import('../components/deprecated/about.vue')
    }, {
      path: "/home",
      name: "home",
      component: () => import('../components/home/index.vue')
    }]
  }
]

const router = new VueRouter({
  mode: "history",
  routes: routes,
  scrollBehavior(to, from, savedPosition) {
    return { x: 0, y: 0 }
  }
})

const pushRoute = (list) => {
  list.map(item => {
    let obj = {
      path: item.path,
      name: Symbol(item.componentName),
      component: () => import(`@/components${item.component}`)
    }
    router.addRoute('index', obj)
  })
}

router.beforeEach((to, from, next) => {
  if (!to.name) {
    let list = store.state.routeList
    if (list.length > 0) {
      pushRoute(list)
    } else {
      let arrayList = JSON.parse(localStorage.getItem('routeList'))
      pushRoute(arrayList)
    }
    next({ ...to, replace: true })
  }
  next()
})



export default router
